package cc.ls51.api.utils;

import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class RenderUtil {
    /**
     * 以JSON格式输出
     */
    public void renderJson(Object obj) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //将实体对象转换为JSON Object转换
        sra.getResponse().setContentType("application/json");
        sra.getResponse().setHeader("Cache-Control", "no-store");
        sra.getResponse().setCharacterEncoding("UTF-8");
        try {
            PrintWriter pw=sra.getResponse().getWriter();
            String jsonStr = JSONUtil.parseObj(obj).toString();
            pw.write(jsonStr);
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void renderXml(String obj) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //将实体对象转换为JSON Object转换
        sra.getResponse().setContentType("application/xml");
        sra.getResponse().setHeader("Cache-Control", "no-store");
        sra.getResponse().setCharacterEncoding("UTF-8");
        try {
            PrintWriter pw=sra.getResponse().getWriter();
            pw.write(obj);
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void renderRedirect(String url) {
        try {
            ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // 重定向到文件
            sra.getResponse().sendRedirect(sra.getRequest().getContextPath() + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
